package com.controller;

import java.io.InputStream;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.pojo.User;
import com.service.UserService;

@Controller
public class ChangeTaoCanController {
	@Autowired
	private UserService userService;
	//更改套餐
	@GetMapping("/changeTaoCan")
	public String showChangeTaoCan(Model model) {
		model.addAttribute("message","");
		return "changeTaoCan";
	}
	@PostMapping("/changeTaoCan")
	public String changeTaoCan(@RequestParam String cardNumber,@RequestParam String password,@RequestParam int newTaocanId,Model model)throws Exception {
		User a=userService.getUserByCardNumber(cardNumber);
		if(a==null) {
			model.addAttribute("message","未找到您的卡号，请检查卡号是否正确");
			return "changeTaoCan";
	   }
		
		boolean success=userService.changeTaoCan(cardNumber, password, newTaocanId);
		if(success) {
		   if(newTaocanId==a.getTaocan()) {
			   model.addAttribute("message","对不起，您已经是该套餐，无需更换");
			    return "changeTaoCan";
		   }
		}
		if(success) {
			User updatedUser=userService.getUserByCardNumber(cardNumber);
			int tongji=userService.recalculateConsumption(cardNumber, newTaocanId);
			model.addAttribute("tongji",tongji);
			model.addAttribute("cardNumber",cardNumber);
			model.addAttribute("a",updatedUser);
			model.addAttribute("message","套餐更换成功");
			return "recalculateConsumption";
		}else {
			model.addAttribute("message","套餐更换失败，请检查密码或余额");
		}
		
		return "changeTaoCan";
		
	}
	//统计实际消费数据以及当月消费金额
	 @GetMapping("/recalculateConsumption")
	    public String showrecalculateConsumption(){
	        return "recalculateConsumption";
	    }
	@RequestMapping(value="/recalculateConsumption",method=RequestMethod.POST)
	public String getRecalculateConsumption(@RequestParam String cardNumber,Model model,@RequestParam int newTaocanId) {
		int tongji=userService.recalculateConsumption(cardNumber,newTaocanId);
		
		User a=userService.getUserByCardNumber(cardNumber);
        	 model.addAttribute("tongji",tongji);
 		     model.addAttribute("cardNumber",cardNumber);
	         model.addAttribute("a",a);
		     return "recalculateConsumption";
    	    
        
		
       
		
	}
	
	
	

}
